/**
 * IosMulitSelect
 * @param 
 */
(function() {
	iosSelectUtil = {
		isArray: function(arg1) {
			return Object.prototype.toString.call(arg1) === '[object Array]';
		},
		isFunction: function(arg1) {
			return typeof arg1 === 'function';
		},
		attrToData: function(dom, index) {
			var obj = {};
			for (var p in dom.dataset) {
				obj[p] = dom.dataset[p];
			}
			obj['dom'] = dom;
			obj['atindex'] = index;
			return obj;
		},
		attrToHtml: function(obj) {
			var html = '';
			for (var p in obj) {
				html += 'data-' + p + '="' + obj[p] + '"';
			}
			return html;
		},
		contains: function(arr, obj){
			var i = arr.length;  
			while (i--) {  
			    if (arr[i] === obj) {  
			       return true;  
			    }  
			}  
		    return false;  
		}
	};
	// Layer
	function Layer(html, opts) {
		if (!(this instanceof Layer)) {
			return new Layer(html, opts);
		}
		this.html = html;
		this.opts = opts;
		var el = document.createElement('div');
		el.className = 'olay';
		// var layer_el = $('<div class="layer"></div>');
		var layer_el = document.createElement('div');
		layer_el.className = 'layer';
		this.el = el;
		this.layer_el = layer_el;
		this.init();
	}
	Layer.prototype = {
		init: function() {
			this.layer_el.innerHTML = this.html;
			if (this.opts.container && document.querySelector(this.opts.container)) {
				document.querySelector(this.opts.container).appendChild(this.el);
			}
			else {
				document.body.appendChild(this.el);
			}
			this.el.appendChild(this.layer_el);
			this.el.style.height = Math.max(document.documentElement.getBoundingClientRect().height, window.innerHeight);
			if (this.opts.className) {
				this.el.className += ' ' + this.opts.className;
			}
			this.bindEvent();
		},
		bindEvent: function() {
			var sureDom = this.el.querySelectorAll('.sure');
			var closeDom = this.el.querySelectorAll('.close');
			var self = this;
			for (var i = 0, len = sureDom.length; i < len; i++) {
				sureDom[i].addEventListener('click', function(e) {
					self.close();
				});
			}
			for (var i = 0, len = closeDom.length; i < len; i++) {
				closeDom[i].addEventListener('click', function(e) {
					self.close();
				});
			}
		},
		close: function() {
			if (this.el) {
				this.el.parentNode.removeChild(this.el);
				this.el = null;
			}
		}
	}
	function IosMultiSelect(data, options) {
		if (!iosSelectUtil.isArray(data) || data.length === 0) {
			return;
		}
		this.data = data;
		this.options = options;
		this.typeBox = 'one-level-box';
		this.callback = options.callback;
		this.title = options.title || '';
		this.options.itemHeight = options.itemHeight || 35;
		this.options.itemShowCount = options.itemShowCount || 5;
		this.options.headerHeight = options.headerHeight || 44;
		if (this.options.cssUnit !== 'px' && this.options.cssUnit !== 'rem') {
			this.options.cssUnit = 'px';
		}
		this.setBase();
		this.init();
	};

	IosMultiSelect.prototype = {
		init: function() {
			this.initLayer();
			// 选中元素的信息
			this.selectOneObj = [];
			this.setOneLevel(this.options.defaultIds || []);
		},
		initLayer: function() {
			var self = this;
			var all_html = [
				'<header style="height: ' + this.options.headerHeight + this.options.cssUnit + '; line-height: ' + this.options.headerHeight + this.options.cssUnit + '" class="iosselect-header">',
					'<h2 id="iosSelectTitle"></h2>',
					'<a style="height: ' + this.options.headerHeight + this.options.cssUnit + '; line-height: ' + this.options.headerHeight + this.options.cssUnit + '" href="javascript:void(0)" class="close">取消</a>',
					'<a style="height: ' + this.options.headerHeight + this.options.cssUnit + '; line-height: ' + this.options.headerHeight + this.options.cssUnit + '" href="javascript:void(0)" class="sure">确定</a>',
				'</header>',
				'<section class="iosselect-box">',
					'<div class="one-level-contain" id="oneLevelContain">',
						'<ul class="select-one-level">',
						'</ul>',
					'</div>',
				'</section>',
				'<div class="ios-select-loading-box" id="iosSelectLoadingBox">',
				    '<div class="ios-select-loading"></div>',
				'</div>'
			].join('\r\n');
			this.iosSelectLayer = new Layer(all_html, {
				className: 'ios-select-widget-box ' + this.typeBox + (this.options.addClassName? ' ' + this.options.addClassName: ''),
				container: this.options.container || ''
			});

			this.iosSelectTitleDom = this.iosSelectLayer.el.querySelector('#iosSelectTitle');
			this.iosSelectLoadingBoxDom = this.iosSelectLayer.el.querySelector('#iosSelectLoadingBox');
			if (this.options.title) {
				this.iosSelectTitleDom.innerHTML = this.options.title;
			}

			this.oneLevelContainDom = this.iosSelectLayer.el.querySelector('#oneLevelContain');
			this.oneLevelUlContainDom = this.iosSelectLayer.el.querySelector('.select-one-level');

			this.iosSelectLayer.el.querySelector('.layer').style.height = this.options.itemHeight * this.options.itemShowCount + this.options.headerHeight + this.options.cssUnit;

			this.oneLevelContainDom.style.height = this.options.itemHeight * this.options.itemShowCount + this.options.cssUnit;

			this.offsetTop = document.body.scrollTop;
			document.body.classList.add('ios-select-body-class');
			window.scrollTo(0, 0);

			this.scrollOne = new IScroll('#oneLevelContain', {
				probeType: 3,
				bounce: false
			});
			
			

			// 取消 确认 事件
			this.closeBtnDom = this.iosSelectLayer.el.querySelector('.close');
			this.closeBtnDom.addEventListener('click', function(e) {
				if (document.body.classList.contains('ios-select-body-class')) {
					document.body.classList.remove('ios-select-body-class');
				}
				window.scrollTo(0, self.offsetTop);
			});

			this.selectBtnDom = this.iosSelectLayer.el.querySelector('.sure');
			this.selectBtnDom.addEventListener('click', function(e) {
				if (document.body.classList.contains('ios-select-body-class')) {
					document.body.classList.remove('ios-select-body-class');
				}
				window.scrollTo(0, self.offsetTop);
				self.callback && self.callback(self.selectOneObj);
			});
		},
		loadingShow: function() {
			this.options.showLoading && (this.iosSelectLoadingBoxDom.style.display = 'block');
		},
		loadingHide: function() {
			this.iosSelectLoadingBoxDom.style.display = 'none';
		},
		getOneLevel: function() {
			return this.data;
		},
		setOneLevel: function(defaultIds) {
			if (iosSelectUtil.isArray(this.data)){
				var oneLevelData = this.getOneLevel();
				this.renderOneLevel(defaultIds, oneLevelData);
			}
			else {
				throw new Error('data format error');
			}
		},
		renderOneLevel: function(defaultIds, oneLevelData) {
			var oneHtml = '';
			var self = this;
			oneLevelData.forEach(function(v, i, o) {
				var hasAtId = defaultIds.some(function(vv, ii, oo) {
					return v.id == vv;
				});
				if (hasAtId) {
					oneHtml += '<li style="opacity:1;font-size:16px;border-bottom:1px solid #ddd;text-align:left;padding-left:15px;height: ' + this.options.itemHeight + this.options.cssUnit + '; line-height: ' + this.options.itemHeight + this.options.cssUnit +';"' + iosSelectUtil.attrToHtml(v) + ' class="at">' + v.value + '<i style="float:right;padding-right:20px;" class="icon ion-ios-checkmark-outline"></i></li>';
				} else {
					oneHtml += '<li style="opacity:1;font-size:16px;border-bottom:1px solid #ddd;text-align:left;padding-left:15px;height: ' + this.options.itemHeight + this.options.cssUnit + '; line-height: ' + this.options.itemHeight + this.options.cssUnit +';"' + iosSelectUtil.attrToHtml(v) + '>' + v.value + '<i style="float:right;padding-right:20px;" class="icon ion-ios-checkmark-outline"></i></li>';
				}//ion-ios-checkmark
			}.bind(this));
			this.oneLevelUlContainDom.innerHTML = oneHtml;
			this.scrollOne.refresh();
			
			var pdoms = this.oneLevelUlContainDom.querySelectorAll('li');
			var atColor = 'red';
			for(var i = 0;i < pdoms.length;i++){
				var pdom = pdoms[i];
				pdom.addEventListener('click', function(e) {
					if (this.classList.contains('at')) {
						this.classList.remove('at');
						this.style.color = '';
						var selected = iosSelectUtil.attrToData(this,0);
						for(var i in self.selectOneObj){
							if(self.selectOneObj[i].id == selected.id){
								self.selectOneObj.splice(i,1);
								return;
							}
						}
					}else{
						this.classList.add('at');
						this.style.color = atColor;
						self.selectOneObj.push(iosSelectUtil.attrToData(this,0));
					}
				});
				if(pdom.classList.contains('at')){
					this.selectOneObj.push(iosSelectUtil.attrToData(pdom,0));
					pdom.style.color = atColor;
				}
			}
		}, 
	    changeClassName: function(levelContainDom, plast) {
	    	var pdom;
	    	if (this.options.itemShowCount === 3) {
	    		pdom = levelContainDom.querySelector('li:nth-child(' + (plast + 1) + ')');
				pdom.classList.add('at');
	    	}
	    	return pdom;
	    },
	    setBase: function() {
			if (this.options.cssUnit === 'rem') {
				var dltDom = document.documentElement;
				var dltStyle = window.getComputedStyle(dltDom, null);
				var dltFontSize = dltStyle.fontSize;
				try {
					this.baseSize = /\d+(?:\.\d+)?/.exec(dltFontSize)[0];
				}
				catch(e) {
					this.baseSize = 1;
				}
			}
			else {
				this.baseSize = 1;
			}
		}
	}
	if (typeof module != 'undefined' && module.exports) {
		module.exports = IosMultiSelect;
	} else if (typeof define == 'function' && define.amd) {
		define(function() {
			return IosMultiSelect;
		});
	} else {
		window.IosMultiSelect = IosMultiSelect;
	}
})();